package xpn.platform.modules.todo.donelink;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xpn.platform.modules.sys.user.SysUser;
import xpn.platform.modules.sys.user.SysUserDAO;
import xpn.platform.modules.sys.user.SysUserService;
import xpn.platform.modules.todo.todolink.TodoLink;
import xpn.platform.modules.todo.todolink.TodoLinkDAO;
import xpn.platform.modules.todo.wsdl.TodosCall;

import com.google.common.base.Strings;

import lombok.extern.slf4j.Slf4j;

/**
 * 待办 服务实现类
 *
 * @author duwei
 */
@Slf4j
@Service
public class DonLinkServiceImpl implements DoneLinkService {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    private TodoLinkDAO todoLinkDAO;
    @Autowired
    private DoneLinkDAO doneLinkDAO;

    @Autowired
    TodosCall todosCall;

    @Autowired
    SysUserDAO sysUserDAO;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void toTodo(String taskId) {
        if (!Strings.isNullOrEmpty(taskId)) {
            DoneLink doneLink = doneLinkDAO.findByTaskId(taskId);
            if (doneLink != null) {
                TodoLink todoLink = createTodoLink(doneLink);
                doneLinkDAO.delete(doneLink);
                todoLinkDAO.save(todoLink);
                SysUser sendee = sysUserDAO.getOne(Long.parseLong(doneLink.getSendeeId()));
                /*try {
                    todosCall.revert(doneLink.getLinkUrl(), sendee.getUserCode());
                    log.info("连接多米诺平台完成TODO[" + doneLink.getSubject() + "]成功");
                } catch (RemoteException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                    log.error("连接多米诺平台完成TODO[" + doneLink.getSubject() + "]失败", e);
                }*/
            }
        }
    }

    /**
     * 根据待办创建已办
     *
     * @param doneLink
     */
    private TodoLink createTodoLink(DoneLink doneLink) {
        TodoLink todoLink = new TodoLink();
        BeanUtils.copyProperties(doneLink, todoLink, "id");
        return todoLink;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchToTodo(String[] doneIds) {
        if (doneIds.length > 0) {
            for (String id : doneIds) {
                DoneLink doneLink = doneLinkDAO.getById(Long.parseLong(id));
                if (doneLink != null) {
                    TodoLink todoLink = createTodoLink(doneLink);
                    doneLinkDAO.delete(doneLink);
                    todoLinkDAO.save(todoLink);
                }
            }
        }
    }
}
